package com.sparrow.manage.util;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class NetFileHandler {

    private static Logger logger = LoggerFactory.getLogger("sparrow");

    /**
     * 获取文件大小，单位KB
     * @param file
     * @return
     */
    public static String getFileSizeToDouble(MultipartFile file) {
        String fileSize = "0KB";
        if (null != file) {
            long size = file.getSize();
            String kbSize = String.format("%.1f", (double)size/1024);
            fileSize = kbSize + "KB";
        }
        return fileSize;
    }

    /**
     * 获取文件大小，单位KB
     * @param inputStream
     * @return
     */
    public static String getFileSizeToDouble(InputStream inputStream) throws IOException {
        if(inputStream == null){
            throw new IllegalArgumentException("inputStream is null.");
        }
        int size = inputStream.available();
        String kbSize = String.format("%.1f", (double)size/1024);
        return kbSize + "KB";
    }

    /**
     * @param inputStream
     * @param quality
     * @return
     */
    public static ByteArrayOutputStream compressImage(InputStream inputStream, double quality){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            Thumbnails.of(inputStream).scale(1).outputQuality(quality).toOutputStream(out);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return out;
    }

}
